<?php
/*
 * Created on Jan 7, 2011
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
class CSVFileParser
{
	private $hasError		= false;
	private $errorInfo		= '';
	
	private $rowIndex 		= 0;
	
	private $arrTitle 		= array();
	private $arrRowList 	= array();
	
	private $arrCurrentRow 	= array();
	
	private $arrNameList	= array();
	
	function CSVFileParser()
	{
	}
	
	public function parser($filePath)
	{
		$isFileExisted = file_exists($filePath);
		if($isFileExisted){
			$row 		= 0;
			$nameIndex 	= 0;
			
			$handle = fopen($filePath, "r");
			while ($data = fgetcsv($handle)) {
			    $num = count($data);
	
			    $row++;
			    
			    if($row == 1){
			    	for ($c = 0; $c < $num; $c++) {
			        	$this->arrTitle[] = strtolower(trim($data[$c]));
			    	}
			    	
			    	$nameIndex = $this->getKeyIndex('name');
			    	if($nameIndex == -1){
			    		$errorInfo = 'not found name index.';
			    		
			    		echo $errorInfo . '<br>';
			    	}
			    }else{
			    	$arrData = array();
			    	for ($c = 0; $c < $num; $c++) {
			        	$arrData[] = trim($data[$c]);
			    	}
			    	
			    	$this->arrRowList[] = $arrData;
			    	
			    	$this->arrNameList[] = trim($data[$nameIndex]);
			    	
			    	if($row == 2){
			    		$this->arrCurrentRow = $arrData;
			    	}
			    }
			}
			
			fclose($handle);
		}else{
			$errorInfo = "file existed : $filePath";
			    		
			echo $errorInfo . '<br>';
		}
	}
	
	public function getNameList()
	{
		return $this->arrNameList;	
	}
	
	public function isHasError()
	{
		return $this->hasError;	
	}
	
	public function isEnd()
	{
		if($this->rowIndex == count($this->arrRowList))
			return true;
		else
			return false;	
	}
	
	public function nextLine()
	{
		$this->arrCurrentRow = $this->arrRowList[$this->rowIndex];
		
		$this->rowIndex++;
		
		if($this->rowIndex > count($this->arrRowList))
			$this->rowIndex = count($this->arrRowList);
	}
	
	public function getValue($key)
	{
		$keyIndex = $this->getKeyIndex($key);
		
		if($keyIndex != -1){
			return $this->arrCurrentRow[$keyIndex];
		}else
			return '';		
	}
	
	public function getKeyIndex($key)
	{
		if(in_array($key, $this->arrTitle)){
			$arrKeys = array_keys($this->arrTitle, $key);
			
			return $arrKeys[0];
		}else{
			return -1;
		}
	}
}
?>
